﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Kakehashi.Device;
using Kakehashi;
using System.Threading;
using System.Net;


namespace Demo
{
    public partial class SampleServer : Form
    {
        TDS01V _tds;
        GPS52D _gps;
        Thread _serverThread;

        public SampleServer()
        {
            InitializeComponent();
            Config config = ConfigLoader.Instance.Load();
            _tds = new TDS01V(config.TDSCOMPort);
            _gps = new GPS52D(config.GPSCOMPort);
            _serverThread = new Thread(HttpServer);
            _serverThread.IsBackground = true;
            _serverThread.Start();
        }

        private void HttpServer()
        {
            string prefix = "http://*:8080/";

            HttpListener listener = new HttpListener();
            listener.Prefixes.Add(prefix);
            listener.Start();

            while (true)
            {
                HttpListenerContext context = listener.GetContext();
                HttpListenerRequest req = context.Request;
                HttpListenerResponse res = context.Response;

                string raw = req.RawUrl;
                string content="";

                switch (raw)
                {
                    case "/td":
                        content = _tds.GetData().ToString();
                        break;
                    case "/gp":
                        content = _gps.GetData().ToString();
                        break;
                    default:
                        content = "NA";
                        break;
                }
                byte[] data = Encoding.Unicode.GetBytes(content);
                res.OutputStream.Write(data, 0, data.Length);
                res.Close();
            }

        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.label1.Text = _tds.GetData().ToString();
            this.label2.Text = _gps.GetData().ToString();
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {

        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {

        }
    }
}
